//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package io.renren.utils.rapid;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.*;

public class FreemarkerHelper {

    private static Logger logger = LoggerFactory.getLogger(FreemarkerHelper.class);

    private static Configuration configuration;
    private static List<String> templates;

    public FreemarkerHelper() {
    }

    public static List<String> getAvailableAutoInclude(Configuration conf, List<String> autoIncludes) {
        List<String> results = new ArrayList();
        Iterator i$ = autoIncludes.iterator();

        while(i$.hasNext()) {
            String autoInclude = (String)i$.next();

            try {
                Template t = new Template("__auto_include_test__", new StringReader("1"), conf);
                conf.setAutoIncludes(Arrays.asList(autoInclude));
                t.process(new HashMap(), new StringWriter());
                results.add(autoInclude);
            } catch (Exception var6) {
            }
        }

        return results;
    }

    public static void processTemplate(Template template, Map model, File outputFile, String encoding) throws IOException, TemplateException {
        Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), encoding));
        template.process(model, out);
        out.close();
    }

    public void processTemplate(Writer out) throws TemplateException, IOException {
        freemarker.template.Configuration cfg = FreemarkerHelper.newFreeMarkerConfiguration();
        List<String> templates = getTemplates();

    }

    public static String processTemplateString(String templateString, Map model, Configuration conf) {
        StringWriter out = new StringWriter();

        try {
            Template template = new Template("templateString...", new StringReader(templateString), conf);
            template.process(model, out);
            return out.toString();
        } catch (Exception var5) {
            throw new IllegalStateException("cannot process templateString:" + templateString + " cause:" + var5, var5);
        }
    }

    public static synchronized Configuration newFreeMarkerConfiguration() throws IOException {

        if (configuration == null) {

            Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);

            try {
                File file = ResourceUtils.getFile("classpath:template");


                logger.info("init tempatePath " + file.getPath());
                cfg.setDirectoryForTemplateLoading(file);
            } catch (Exception e) {
                logger.error(e.getMessage());

                cfg.setClassLoaderForTemplateLoading(FreemarkerHelper.class.getClassLoader(), "template");

            }


            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

            configuration = cfg;

        }

        return configuration;

    }

    public static List<String> getParentPaths(String templateName, String suffix) {
        String[] array = StringHelper.tokenizeToStringArray(templateName, "\\/");
        List<String> list = new ArrayList();
        list.add(suffix);
        list.add(File.separator + suffix);
        String path = "";

        for(int i = 0; i < array.length; ++i) {
            path = path + File.separator + array[i];
            list.add(path + File.separator + suffix);
        }

        return list;
    }

    public static synchronized List<String> getTemplates() throws IOException {

        if (templates != null) {
            return templates;
        }

        List<String> templates = new ArrayList<String>();

        File file = null;

        try {
            file = ResourceUtils.getFile("classpath:template");
            logger.info("templates root dir exists? {}", file.exists());

            String rootPath = file.getPath();

            if (file.exists() && file.isDirectory()) {

                Iterator<File> fileList = FileUtils.iterateFiles(file, new String[]{"ftl"}, true);
                while (fileList.hasNext()) {
                    File file1 = fileList.next();
                    templates.add(file1.getAbsolutePath().substring(rootPath.length() + 1));
                }
            }

        } catch (Exception e) {

            String filePath = ClassUtils.getDefaultClassLoader().getResource("/template").getPath();
            logger.info("templates root jar dir： {}", filePath );

            File localFile = new File(filePath);
            String rootPath = localFile.getPath();
            logger.info("templates root jar dir exist： {}", file.exists() && file.isDirectory() );

            if (file.exists() && file.isDirectory()) {

                Iterator<File> fileList = FileUtils.iterateFiles(file, new String[]{"ftl"}, true);
                while (fileList.hasNext()) {
                    File file1 = fileList.next();
                    logger.info("templates root jar file： {}", file1.getPath() );
                    templates.add(file1.getAbsolutePath().substring(rootPath.length() + 1));
                }
            }
        }



        return templates;
    }

}
